package com.tust.androidbbsclient;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.tust.androidbbsclient.domain.User;
import com.tust.androidbbsclient.fragment.ExploreFragment;
import com.tust.androidbbsclient.fragment.MessageFragment;
import com.tust.androidbbsclient.fragment.PersonFragment;
import com.tust.androidbbsclient.fragment.SubmitFragment;
import com.tust.androidbbsclient.tool.Application;
import com.tust.androidbbsclient.tool.Tool;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private Toast toast;
    private long exitTime;
    private String Uname;

    //用于在线程间传递消息
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);//获取子线程传递的消息
            if (msg.what == 1) {//更新用户禁言状态请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("检查用户禁言状态：" + strMsg);

                switch (strMsg) {
                    case "serverFalse":
                        showToast(Tool.addEmoji() + "服务器通信失败！");
                        break;
                    case "databaseFalse":
                        showToast(Tool.addEmoji() + "服务器端错误！");
                        break;
                    case "userNotBan":
                        break;
                    case "userBaning":
                        showToast(Tool.addEmoji() + "您已被禁言！");
                        break;
                    case "updateUbanFalse":
                        showToast(Tool.addEmoji() + "更新用户禁言状态失败！");
                        break;
                    case "updateUbanSuccess":
                        break;
                }
            } else if (msg.what == 2) {//获取用户信息请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("获取用户信息：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //从意图中获得用户名
        Uname = this.getIntent().getStringExtra("Uname");

        //发送更新用户禁言状态请求子线程
        new Thread() {
            @Override
            public void run() {
                OutputStream outputStream = null;
                BufferedReader bufferedReader = null;
                String data = "";
                try {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符

                    URL url = new URL(Tool.InetAddress + "/updateUbanStatus.do");//请求地址
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //连接类相关设置
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(3000);//连接服务器超时
                    connection.setReadTimeout(3000);//从服务器读取数据超时
                    connection.setDoInput(true);//允许写入，从服务端读取结果流
                    connection.setDoOutput(true);//允许写出，开启Post请求体
                    connection.setUseCaches(false);//不使用Cache
                    connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                    connection.connect();//连接网络
                    String params = "Uname=" + Uname;//请求体内容
                    outputStream = connection.getOutputStream();//请求输出流
                    outputStream.write(params.getBytes());

                    int code = connection.getResponseCode();//获得响应状态码
                    if (code == 200) {//返回状态码200，连接成功
                        bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        data = bufferedReader.readLine();

                        handlerMsg.obj = data;//写入线程传递消息
                    } else handlerMsg.obj = "serverFalse";//服务器通信失败
                    connection.disconnect();//关闭连接

                    handler.sendMessage(handlerMsg);//发送线程消息

                    //若更新用户禁言状态完成，获取用户信息
                    if (data.equals("userNotBan") || data.equals("updateUbanSuccess") || data.equals("userBaning")) {
                        //发送获取用户信息请求子线程
                        new Thread() {
                            @Override
                            public void run() {
                                OutputStream outputStreamChild = null;
                                BufferedReader bufferedReaderChild = null;
                                String dataChild = "";
                                try {
                                    Message handlerMsgChild = Message.obtain();//构造Message对象，用于向主线程传递消息
                                    handlerMsgChild.what = 2;//增加handlerMsg标识符

                                    URL urlChild = new URL(Tool.InetAddress + "/getUserInfo.do");//请求地址
                                    HttpURLConnection connectionChild = (HttpURLConnection) urlChild.openConnection();

                                    //连接类相关设置
                                    connectionChild.setRequestMethod("POST");
                                    connectionChild.setConnectTimeout(3000);//连接服务器超时
                                    connectionChild.setReadTimeout(3000);//从服务器读取数据超时
                                    connectionChild.setDoInput(true);//允许写入，从服务端读取结果流
                                    connectionChild.setDoOutput(true);//允许写出，开启Post请求体
                                    connectionChild.setUseCaches(false);//不使用Cache
                                    connectionChild.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                    connectionChild.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                                    connectionChild.connect();//连接网络
                                    String paramsChild = "Uname=" + Uname;//请求体内容
                                    outputStreamChild = connectionChild.getOutputStream();//请求输出流
                                    outputStreamChild.write(paramsChild.getBytes());

                                    int codeChild = connectionChild.getResponseCode();//获得响应状态码
                                    if (codeChild == 200) {//返回状态码200，连接成功
                                        bufferedReaderChild = new BufferedReader(new InputStreamReader(connectionChild.getInputStream()));
                                        dataChild = bufferedReaderChild.readLine();

                                        //解析JSON字符串
                                        JSONArray jsonArray = new JSONArray(dataChild);
                                        User user = new User(
                                                Integer.parseInt(jsonArray.getJSONObject(0).getString("uid")),
                                                jsonArray.getJSONObject(0).getString("uname"),
                                                jsonArray.getJSONObject(0).getString("upasswd"),
                                                jsonArray.getJSONObject(0).getString("ugender"),
                                                jsonArray.getJSONObject(0).getString("uint"),
                                                Integer.parseInt(jsonArray.getJSONObject(0).getString("ufavorPrivacy")),
                                                Integer.parseInt(jsonArray.getJSONObject(0).getString("ucollPrivacy")),
                                                Integer.parseInt(jsonArray.getJSONObject(0).getString("ubanLevel")),
                                                jsonArray.getJSONObject(0).getString("ubanTime")
                                        );

                                        //向Application插入用户信息
                                        Application application = (Application) getApplication();
                                        application.addUser(user);

                                        handlerMsgChild.obj = dataChild;//写入线程传递消息
                                    } else handlerMsgChild.obj = "serverFalse";//服务器通信失败
                                    connectionChild.disconnect();//关闭连接

                                    handler.sendMessage(handlerMsgChild);//发送线程消息
                                } catch (IOException e) {
                                    Message handlerMsgChild = Message.obtain();//构造Message对象，用于向主线程传递消息
                                    handlerMsgChild.what = 2;//增加handlerMsg标识符
                                    handlerMsgChild.obj = "serverFalse";
                                    handler.sendMessage(handlerMsgChild);

                                    //throw new RuntimeException(e);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                } finally {
                                    try {
                                        if (bufferedReaderChild != null) bufferedReaderChild.close();
                                        if (outputStreamChild != null) {
                                            outputStreamChild.flush();
                                            outputStreamChild.close();
                                        }
                                    } catch (IOException e) {
                                        System.out.println("子线程：finally失败");
                                        //throw new RuntimeException(e);
                                    }
                                }
                            }
                        }.start();
                    }
                } catch (IOException e) {
                    Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                    handlerMsg.what = 1;//增加handlerMsg标识符
                    handlerMsg.obj = "serverFalse";
                    handler.sendMessage(handlerMsg);

                    //throw new RuntimeException(e);
                } finally {
                    try {
                        if (bufferedReader != null) bufferedReader.close();
                        if (outputStream != null) {
                            outputStream.flush();
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        System.out.println("子线程：finally失败");
                        //throw new RuntimeException(e);
                    }
                }
            }
        }.start();

        BottomNavigationView bottomNavigationView = this.findViewById(R.id.bnv_main);
        View bottomNavView = bottomNavigationView.getChildAt(0);

        //重写底部导航栏长按item事件，去除长按Toast
        bottomNavView.findViewById(R.id.item_bottom_nav_explore).setOnLongClickListener(view -> true);
        bottomNavView.findViewById(R.id.item_bottom_nav_submit).setOnLongClickListener(view -> true);
        bottomNavView.findViewById(R.id.item_bottom_nav_message).setOnLongClickListener(view -> true);
        bottomNavView.findViewById(R.id.item_bottom_nav_person).setOnLongClickListener(view -> true);

        //进入主活动时默认调用浏览碎片
        if (savedInstanceState == null) getSupportFragmentManager().beginTransaction().replace(R.id.ll_main_fgm, new ExploreFragment()).commit();

        //底部导航栏选择器监听事件
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment fragment = null;

                switch (item.getItemId()) {
                    case R.id.item_bottom_nav_explore:
                        fragment = new ExploreFragment();
                        break;
                    case R.id.item_bottom_nav_submit:
                        fragment = new SubmitFragment();
                        break;
                    case R.id.item_bottom_nav_message:
                        fragment = new MessageFragment();
                        break;
                    case R.id.item_bottom_nav_person:
                        fragment = new PersonFragment();
                        break;
                }

                System.out.println("Fragment：" + item.toString());
                getSupportFragmentManager().beginTransaction().replace(R.id.ll_main_fgm, fragment).commit();//从Fragment管理器提交事务，切换Fragment
                return true;
            }
        });
    }

    //返回监听事件
    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showToast(Tool.addEmoji() + "再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            this.finishAffinity();
        }
    }

    //Toast消息提示框显示方法
    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}
